  <template>
    <div class="trending-container">
      <div class="trending-header">
        <h2>热门视频</h2>
        <el-select v-model="selectedPeriod" class="period-select" @change="fetchTrendingVideos">
          <el-option label="今日热门" value="today" />
          <el-option label="本周热门" value="week" />
          <el-option label="本月热门" value="month" />
        </el-select>
      </div>

      <div class="trending-content" v-loading="loading">
        <!-- 热门分类 -->
        <!-- Removed trending categories section -->

        <!-- 视频列表 -->
        <div v-if="trendingVideos.length === 0" class="empty-state">
          <el-empty description="暂无热门视频" />
        </div>
        <div v-else class="video-list">
          <div v-for="(video, index) in trendingVideos" :key="video._id" class="video-item">
            <div class="rank-number">#{{ index + 1 }}</div>
            <div class="video-card" @click="goToVideo(video._id)">
              <div class="thumbnail">
                <img :src="video.thumbnail" :alt="video.title">
                <span class="duration">{{ formatDuration(video.duration) }}</span>
                <div class="views-badge">
                  <el-icon><View /></el-icon>
                  {{ formatViews(video.views) }}
                </div>
              </div>
              <div class="video-info">
                <h3 class="title">{{ video.title }}</h3>
                <div class="channel-info">
            
                  <el-avatar :size="24" :src="video.user?.avatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
              
                  <span class="channel-name">{{ video.user?.username || '未知用户' }}</span>
                </div>
                <div class="stats">
                  <div class="stat-item">
                    <el-icon><Star /></el-icon>
                    <!-- 修改：使用 video.likes.length -->
                    {{ formatNumber(video.likes?.length || 0) }}
                  </div>
                  <div class="stat-item">
                    <el-icon><ChatDotRound /></el-icon>
                    <!-- 修改：使用 video.comments.length -->
                    {{ formatNumber(video.comments?.length || 0) }}
                  </div>
                  <span class="upload-time">{{ formatDate(video.createdAt) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore && !loading">
          <el-button :loading="loadingMore" @click="loadMore">加载更多</el-button>
        </div>
      </div>
    </div>
  </template>

  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import axios from '@/services/axios'
  import { ElMessage } from 'element-plus'
  import { View, Star, ChatDotRound } from '@element-plus/icons-vue' // Changed to Star

  const router = useRouter()

  // 状态变量
  const loading = ref(false)
  const loadingMore = ref(false)
  const hasMore = ref(true)
  const selectedPeriod = ref('today')
  // Removed selectedCategory and categories
  const page = ref(1)
  const pageSize = 10

  // 视频列表
  const trendingVideos = ref([])

  // 获取热门视频
  const fetchTrendingVideos = async (reset = true) => {
    if (reset) {
      loading.value = true
      trendingVideos.value = []
      page.value = 1
    } else {
      loadingMore.value = true
    }

    try {
      const params = {
        period: selectedPeriod.value,
        page: page.value,
        limit: pageSize
      }

      const response = await axios.get('/api/videos/trending/list', { params })
      // 修改：后端不直接返回 hasMore，根据返回数量判断
      const videos = response.data.videos || []

      if (reset) {
        trendingVideos.value = videos
      } else {
        trendingVideos.value.push(...videos)
      }

      // 修改：根据返回的视频数量判断是否还有更多
      hasMore.value = videos.length === pageSize
      if (hasMore.value) {
        page.value++
      }
    } catch (error) {
      console.error('获取热门视频失败:', error)
      let errorMessage = '获取热门视频失败'
      if (error.response?.data?.error) {
        errorMessage = error.response.data.error
      }
      ElMessage.error(errorMessage)
      hasMore.value = false // 出错时认为没有更多了
    } finally {
      if (reset) {
        loading.value = false
      } else {
        loadingMore.value = false
      }
    }
  }

  // Removed selectCategory function

  // 加载更多
  const loadMore = () => {
    fetchTrendingVideos(false)
  }

  // 跳转到视频页面
  const goToVideo = (videoId) => {
    console.log('Navigating to video with ID:', videoId); // 添加日志
    router.push(`/video/${videoId}`)
  }

  // 格式化视频时长
  const formatDuration = (seconds) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = seconds % 60

    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    }
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  // 格式化观看次数
  const formatViews = (views) => {
    if (views >= 100000000) {
      return (views / 100000000).toFixed(1) + '亿'
    }
    if (views >= 10000) {
      return (views / 10000).toFixed(1) + '万'
    }
    return views
  }

  // 格式化数字（点赞、评论）
  const formatNumber = (num) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M'
    }
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K'
    }
    return num
  }

  // 格式化日期
  const formatDate = (dateString) => {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    const seconds = Math.floor(diff / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)
    const weeks = Math.floor(days / 7)
    const months = Math.floor(days / 30)
    const years = Math.floor(days / 365)

    if (years > 0) {
      return `${years}年前`
    }
    if (months > 0) {
      return `${months}月前`
    }
    if (weeks > 0) {
      return `${weeks}周前`
    }
    if (days > 0) {
      return `${days}天前`
    }
    if (hours > 0) {
      return `${hours}小时前`
    }
    if (minutes > 0) {
      return `${minutes}分钟前`
    }
    return '刚刚'
  }

  // 组件挂载时获取数据
  onMounted(() => {
    fetchTrendingVideos()
  })
  </script>

  <style scoped>
  .trending-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
  }

  .trending-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .trending-header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #0f0f0f;
  }

  .period-select {
    width: 120px;
  }

  .trending-content {
    /* Styles for the main content area */
  }

  .empty-state {
    margin: 60px 0;
    text-align: center;
  }

  .video-list {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
    margin-top: 20px;
  }

  .video-item {
    display: flex;
    margin-bottom: 20px;
    align-items: flex-start;
  }

  .rank-number {
    font-size: 20px;
    font-weight: bold;
    color: #606060;
    width: 40px;
    text-align: center;
    margin-right: 15px;
    margin-top: 10px; /* Adjust alignment */
  }

  .video-card {
    display: flex;
    flex: 1;
    cursor: pointer;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    transition: box-shadow 0.3s ease;
  }

  .video-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .thumbnail {
    position: relative;
    width: 240px; /* Adjust width as needed */
    height: 135px; /* Adjust height based on aspect ratio */
    flex-shrink: 0;
  }

  .thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }

  .duration {
    position: absolute;
    bottom: 5px;
    right: 5px;
    background-color: rgba(0, 0, 0, 0.8);
    color: #fff;
    font-size: 12px;
    padding: 2px 4px;
    border-radius: 2px;
  }

  .views-badge {
    position: absolute;
    top: 5px;
    left: 5px;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 4px;
    display: flex;
    align-items: center;
  }

  .views-badge .el-icon {
    margin-right: 3px;
  }

  .video-info {
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
  }

  .title {
    font-size: 16px;
    font-weight: 500;
    color: #0f0f0f;
    margin: 0 0 8px 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .channel-info {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }

  .channel-name {
    font-size: 13px;
    color: #606060;
    margin-left: 8px;
  }

  .stats {
    display: flex;
    align-items: center;
    font-size: 13px;
    color: #606060;
  }

  .stat-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }

  .stat-item .el-icon {
    margin-right: 4px;
    font-size: 14px;
  }

  .upload-time {
    margin-left: auto; /* Push time to the right */
  }

  .load-more {
    text-align: center;
    margin-top: 20px;
  }

  </style>